package adventure.commands;

import adventure.*;
import player.*;
import colour.ColourUtil;

import java.util.Random;

/**
 *
 * @author Michael Hanns
 *
 */
public class Flee extends AbstractCommand {

    private Random r;

    public Flee(Adventure a) {
        super(a, new String[]{"FLEE"});
        r = new Random();
    }

    @Override
    public String validateAndExecute(Player p, String[] args) {
        if (args.length == 1) {
            return flee(p);
        } else {
            return "Command not recognised.";
        }
    }

    private String flee(Player player) {
        if (player.inCombat()) {
            int rint = r.nextInt(6);
            String dir = "";
            String output = "";

            // Random number determines direction (NESWUD) and sets dir accordingly.
            switch (rint) {
                case 0:
                    dir = "north";
                    break;
                case 1:
                    dir = "east";
                    break;
                case 2:
                    dir = "south";
                    break;
                case 3:
                    dir = "west";
                    break;
                case 4:
                    dir = "up";
                    break;
                case 5:
                    dir = "down";
            }

            if (!rooms.isBlocked(player.x(), player.y(), player.z(), dir.charAt(0))
                    && !rooms.isClosed(player.x(), player.y(), player.z(), dir.charAt(0))) {
                if (dir.equals("up") || dir.equals("down")) {
                    output += "\nYou escape " + dir + "!";
                    output += "\n\n";
                    out.broadcastLocalToPlayer(player,
                            ColourUtil.colourise(player.getName(), ColourUtil.magenta)
                            + " has escaped " + dir + "!");
                } else {
                    output += "\nYou escape to the " + dir + "!";
                    output += "\n\n";
                    out.broadcastLocalToPlayer(player,
                            ColourUtil.colourise(player.getName(), ColourUtil.magenta)
                            + " has escaped to the " + dir + "!");
                }
                player.stopFighting();
                rooms.stopFighting(player);
                rooms.movePlayer(player, dir.charAt(0));
                output += adv.printRoom(player);

                return output;
            } else {
                out.broadcastLocalToPlayer(player,
                            ColourUtil.colourise(player.getName(), ColourUtil.magenta)
                            + " fumbles around in a panic, trying to escape!");
                return "\nYou fumble around in a panic and fail to find the exit!";
            }
        } else {
            return "\nYou are not in combat!";
        }
    }
}
